package com.cb.controller.member.user;


import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.cb.common.util.EncryptUtil;
import com.cb.common.webapp.context.RequestContext;
import com.cb.core.controller.BaseFormController;
import com.cb.domain.model.system.SystemHelp;
import com.cb.domain.model.user.UserAccount;
import com.cb.domain.service.user.UserManager;

/**
 * 
 * @Author author name
 * Create Time:
 * <p>Class Description Here [TODO]</p>
 */
public class MemberFormController extends BaseFormController {
	
	@Autowired
	private UserManager userManager=null;

	public MemberFormController() {
		 setCommandName("user");
	     setCommandClass(UserAccount.class);
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String userId=request.getParameter("userId");
		UserAccount userInfo = new UserAccount();
		if(StringUtils.isNotBlank(userId)){
			userInfo = userManager.get(Long.valueOf(userId));
		}
		String txtPwd = request.getParameter("txtPwd");
		txtPwd=EncryptUtil.md5Translate(txtPwd);
		String newPassword = request.getParameter("newPassword");
		if(userInfo.getPassword().equals(txtPwd)){
			newPassword=EncryptUtil.md5Translate(newPassword);
			userInfo.setPassword(newPassword);
			userManager.save(userInfo);
			return new ModelAndView(getSuccessView());
		} else{
			request.getSession().setAttribute("msg", "原密码错误!");
			request.getSession().setAttribute("act", "true");
			return new ModelAndView(getCancelView(),"msg", "原密码错误!");
		}
		
		
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {		
		if(request.getSession().getAttribute("act")!=null && request.getSession().getAttribute("act").equals("true")){
			request.getSession().setAttribute("act", "false");
		} else{
			if(request.getSession().getAttribute("msg")!=null)
				request.getSession().removeAttribute("msg");
			if(request.getSession().getAttribute("act")!=null)
				request.getSession().removeAttribute("act");
		}
			
		
		UserAccount account=RequestContext.getCurrentUser();
		UserAccount user=null;
		if(account!=null){
			user=userManager.get(account.getUserId());
		}
		return user;
	}
	
}
